#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "ThreadPool.hpp"

// 实现简单的tcp服务器

// 定义一系列错误码
enum
{
    SOCKRT_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

// 定义常量
const static int defaultsocketfd = -1; // 默认的套接字文件描述符为-1
const static int gbacklog = 16;

class TcpServer;

class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(int port)
        : _port(port), _listensock(defaultsocketfd), _isrunning(false)
    {
    }

    // 初始化服务器
    void InitServer()
    {
        // 1.创建套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKRT_ERROR);
        }
        LOG(DEBUG, "socket success,sockfd is:%d\n", _listensock);

        // 2.bind
        // 把一个套接字和特定的地址以及端口绑定起来
        // 让服务器明确自己要监听哪个网络地址和端口
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (const sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success\n");

        // 3.listen操作
        // 将套接字设置为监听状态，使其能接受客户端的连接请求，listen操作是让服务器开始等待客户端的连接
        n = listen(_listensock, gbacklog);
        if (n < 0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen success\n");

        // bind操作是将套接字和特定的地址及端口绑定，明确服务器监听的位置
        // listen操作是将套接字设置为监听状态，使其能够接收客户端的连接请求
    }

    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link,info:%s:%d,fd:%d\n", client.Ip().c_str(), client.Port(), sockfd);

        std::string clientaddr = "[" + client.Ip() + ":" + std::to_string(client.Port()) + "]# ";
        while (true)
        {
            char inbuffer[1024];
            ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
            // 读取到数据，将其回显给客户端
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << clientaddr << inbuffer << std::endl;

                std::string echo_string = "[server echo]# ";
                echo_string += inbuffer;

                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            // 若客户端关闭链接，退出循环
            else if (n == 0)
            {
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            // 读取数据出错，退出循环
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }

            // sleep(5);
            // break;
        }

        // 关闭套接字的读端
        std::cout << "server开始退出" << std::endl;
        shutdown(sockfd, SHUT_RD);
        std::cout << "shut _ rd" << std::endl;
        // sleep(10);
    }

    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->Service(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }

    // 循环接收客户端连接，
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // accept成功，则返回新的套接字描述符，用于和客户端通信
            int sockfd = accept(_listensock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }

            // 采用多线程
            pthread_t t;
            ThreadData *td = new ThreadData(sockfd, InetAddr(peer), this);
            // 创建一个新线程，线程的入口函数为HandlerSock
            pthread_create(&t, nullptr, HandlerSock, td);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_listensock > defaultsocketfd)
        {
            close(_listensock);
        }
    }

private:
    uint16_t _port;
    // 监听套接字
    // 1.主要用途是监听特定的端口，等待客户端发起连接请求，只负责接收客户端的连接请求，而不处理具体的通信数据
    // 2.当监听套接字接收到客户端的连接请求后，会创建新的套接字来专门处理与客户端的数据通信，这样服务器就也可以同时和多个客户端连接
    int _listensock;
    bool _isrunning;
};
